package com.yuan.blog.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class HttpUtils {

    @Autowired
    private RestTemplate restTemplate;
//    @Value("${blog.web.url}")
//    private String baseUrl;

    public ResponseEntity post(String url, Object data) {
//        1.创建一个请你头对象
        HttpHeaders httpHeaders = new HttpHeaders();

        // 2.本次请求传递的数据格式是JSON
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        // 3、把请求和传递的数据封装到httpEntity中
        HttpEntity httpEntity = new HttpEntity(data, httpHeaders);

        // 4.发送请求携带数据
        ResponseEntity responseEntity = restTemplate.postForEntity(url,
                httpEntity, Object.class);

        return responseEntity;
    }

    public ResponseEntity get(String url) {
        return restTemplate.getForEntity(url, Object.class);
    }
}
